package com.xy.xymall.cart.interceptor;

import com.xy.common.constant.AuthServerConstant;
import com.xy.common.constant.CartConstant;
import com.xy.common.vo.MemberRespVo;
import com.xy.xymall.cart.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author XY
 * @version 1.0
 * @date 2020/10/27 16:09
 * @Description 拦截器，判断用户的登录状态，并封装传递给controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();

    /**
     * 目标方法执行之前拦截
     * @param request
     * @param response
     * @param handler 
     * @author XY 
     * @date 2020/10/27 16:11 
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();
        MemberRespVo memberRespVo = (MemberRespVo)session.getAttribute(AuthServerConstant.LOGIN_USER);
        //如果session里有用户信息，就直接拿
        if(memberRespVo!=null){
            //用户已登录
            userInfoTo.setUserId(memberRespVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                //这里判断，如果没有登录的话，去找有没有临时用户，有的话就设置不是第一次访问
                if(CartConstant.TEMP_USER_COOKIE_NAME.equals(name)){
                    //保存好user-key信息
                    userInfoTo.setUserKey(cookie.getValue());
                    //设置不是第一次访问
                    userInfoTo.setFirst(false);
                }
            }
        }
        //如果没有登录，会创建一个临时用户，这里isFirst为true
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid= UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //目标方法执行之前
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 方法执行之后，分配临时用户，让浏览器保存
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @author XY
     * @date 2020/10/27 16:28
     * @return void
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        //如果是第一次访问就让浏览器保存cookie信息，意思就是没有临时用户
        if(userInfoTo.isFirst()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("xymall.com");
            //过期时间
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
